package ${configs.packagePath}.utils;

import ${configs.packagePath}.common.IBaseResponseCode;
import ${configs.packagePath}.common.R;
import org.springframework.util.StringUtils;

/**
 * <Description>
 * 响应工具类
 * @author Jun Lee
 * @version 1.0
 * @createDate ${date}
 */
public class RR extends R {

    private static ThreadLocal<R> responseThreadLocal = new ThreadLocal();

    private RR() {
        super();
    }

    public static R success() {
        R instance = R.getInstance();
        responseThreadLocal.set(instance);
        return instance;
    }

    public static R fail() {
        R instance = R.getInstance();
        instance.setCode(IBaseResponseCode.ERROR_CODE);
        instance.setMessage(IBaseResponseCode.ERROR_MESSAGE);
        responseThreadLocal.set(instance);
        return instance;
    }

    public static R success(Object object) {
        R instance = R.getInstance();
        if (StringUtils.isEmpty(object)) {
            instance.setMessage(IBaseResponseCode.NOT_FOUND_DATA);
        }else{
            instance.setData(object);
        }
        responseThreadLocal.set(instance);
        return instance;
    }

    public static R isOperation(boolean isSuccess) {
        R instance = R.getInstance();
        if (isSuccess) {
            instance.setMessage(IBaseResponseCode.OPERATION_SUCCESS);
        } else {
            instance.setMessage(IBaseResponseCode.OPERATION_FAILD);
        }
        responseThreadLocal.set(instance);
        return instance;
    }

    public static R customize(Integer code, String message) {
        return customize(code,message,null);
    }


    public static R customize(Integer code, String message, Object object) {
        R instance = R.getInstance();
        instance.setCode(code);
        instance.setMessage(message);
        instance.setData(object);
        responseThreadLocal.set(instance);
        return instance;
    }

    public static R get() {
        return (R)responseThreadLocal.get();
    }

    public static void remove() {
        responseThreadLocal.remove();
    }
}
